<template>
  <el-dialog
    :visible="show"
    :title="'多级下拉选项编辑'"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="content d-flex">
      <div class="select-item flex-1 d-flex flex-column">
        <div class="title">
          一级下拉
        </div>
        <div class="list-content flex-1">
          <div
            v-for="(item, index) in levelOne"
            :key="index"
            class="level-item d-flex justify-content-between align-items-center"
          >
            <i v-if="levelOne.length > 0" class="el-icon-s-order"></i>
            <div @click="inpClick(item, 1)">
              <el-input
                v-model="item.value"
                class="input"
                :class="{
                  input_active: activeItem[0].levelName == item.levelName
                }"
                @input="() => (item.value = item.value.replace(/\s+/g, ''))"
                @blur="inputBlur('levelOne', item.value, index)"
              />
            </div>
            <i
              v-if="levelOne.length > 0"
              class="el-icon-remove handle"
              @click.stop="handleCheckbox('levelOne', item.paremtId, index)"
            />
          </div>
          <el-button
            class="create-btn"
            @click="createBtn(1)"
            icon="el-icon-plus"
            >新增选项</el-button
          >
        </div>
      </div>
      <div class="select-item flex-1 d-flex flex-column">
        <div class="title">
          二级下拉
        </div>
        <div class="list-content flex-1">
          <div
            v-for="(item, index) in levelTwo"
            :key="index"
            class="level-item d-flex justify-content-between align-items-center"
          >
            <i v-if="levelTwo.length > 0" class="el-icon-s-order"></i>
            <div @click="inpClick(item, 2)">
              <el-input
                v-model="item.value"
                class="input"
                :class="{
                  input_active: activeItem[1].levelName == item.levelName
                }"
                @blur="inputBlur('levelTwo', item.value, index)"
              />
            </div>

            <i
              v-if="levelTwo.length > 0"
              class="el-icon-remove handle"
              @click.stop="handleCheckbox('levelTwo', item.paremtId, index)"
            />
          </div>
          <el-button
            class="create-btn"
            @click="createBtn(2)"
            icon="el-icon-plus"
            >添加二级下拉选项</el-button
          >
        </div>
      </div>
      <div class="select-item flex-1 d-flex flex-column">
        <div class="title">
          三级下拉
        </div>
        <div class="list-content flex-1">
          <div
            v-for="(item, index) in levelThree"
            :key="index"
            class="level-item d-flex justify-content-between align-items-center"
          >
            <i v-if="levelThree.length > 0" class="el-icon-s-order"></i>
            <div @click="inpClick(item, 3)">
              <el-input
                v-model="item.value"
                class="input"
                :class="{
                  input_active: activeItem[2].levelName == item.levelName
                }"
                @blur="inputBlur('levelThree', item.value, index)"
              />
            </div>

            <i
              v-if="levelThree.length > 0"
              class="el-icon-remove handle"
              @click.stop="handleCheckbox('levelThree', item.paremtId, index)"
            />
          </div>
          <el-button
            class="create-btn"
            @click="createBtn(3)"
            icon="el-icon-plus"
            >添加三级下拉选项</el-button
          >
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      dialogFormVisible: false,
      levelOne: [],
      levelTwo: [],
      levelThree: [],
      activeItem: [{}, {}, {}] // 选中的数据
    };
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    treeData: {
      type: String | Array,
      default: () => {
        return [];
      }
    }
  },
  computed: {
    // levelOne() {
    //   if (this.treeData.length) {
    //     return JSON.parse(this.treeData);
    //   } else {
    //     return [];
    //   }
    // }
  },
  mounted() {
    this.levelOne = this.treeData.length ? JSON.parse(this.treeData) : [];
  },
  methods: {
    // 创建下拉选项
    createBtn(val) {
      switch (val) {
        case 1:
          const level = this.getLevelIndex(this.levelOne);
          const item = {
            paremtId: null, // 父级id
            level: 1, // 层级
            levelName: "1-" + level, // 层级-下标
            index: level, // 下标
            value: "", // 值
            children: [] // 子集
          };
          this.pushTree(1, null, item);
          break;
        case 2:
          if (this.levelOne.length) {
            const level = this.getLevelIndex(this.levelTwo);
            if (Object.keys(this.activeItem[0]).length) {
              const item = {
                paremtId: this.activeItem[0].level,
                level: 2,
                levelName: "2-" + level,
                index: level,
                value: "",
                children: []
              };
              this.levelTwo.push(item);
              this.pushTree(2, item.paremtId, item);
            } else {
              this.$message.error("当前没有选中的一级选项");
              return;
            }
          } else {
            this.$message.error("请先创建一级下拉选项");
          }
          break;
        case 3:
          if (this.levelTwo.length) {
            const level = this.getLevelIndex(this.levelThree);
            if (Object.keys(this.activeItem[1]).length) {
              const item = {
                paremtId: this.activeItem[1].level,
                level: 3,
                levelName: "3-" + level,
                value: "",
                children: []
              };
              this.levelThree.push(item);
              this.pushTree(3, item.paremtId, item);
            } else {
              this.$message.error("当前没有选中的二级选项");
              return;
            }
          } else {
            this.$message.error("请先创建二级下拉选项");
          }
          break;
      }
    },

    /**
     * 判断是否有存在的下标 获取新下标
     * @param {*} data 数据
     */
    getLevelIndex(data) {
      let index = data.length + 1;
      for (let i = 0; i < data.length; i++) {
        // 如果有存在的下标，说明有删除操作
        if (index === data[i].index) {
          return data[data.length - 1].index + 1;
        }
      }
      // 没有存在的直接返回数据长度+1的下标
      return index;
    },

    /**
     * 树形结构存储
     * @param {*} level 存储层级
     * @param {*} paremtId 父级
     * @param {*} item 存储的数据
     */
    pushTree(level, paremtId, item) {
      switch (level) {
        case 1:
          this.levelOne.push(item);
          break;
        case 2:
          // 循环一级找到二级的父级
          this.levelOne.forEach((it, i) => {
            if (it.levelName === paremtId) {
              this.levelOne[i].children.push(item);
            }
          });
          break;
        case 3:
          // 循环一级找到二级的父级
          this.levelOne.forEach((it, i) => {
            it.children.forEach((p, j) => {
              if (p.levelName === paremtId) {
                this.levelOne[i].children[j].push(item);
              }
            });
          });
          break;
      }
    },

    /** 选项点击
     * @param {*} item 点击的某一项
     * @param {*} index 点击的下标
     */
    inpClick(item, index) {
      this.activeItem[index - 1] = item;
      switch (index) {
        case 1:
          this.levelTwo = item.children;
          this.levelThree = [];
          this.activeItem.splice(1, 2, {}, {});
          break;
        case 2:
          this.levelThree = item.children;
          this.activeItem.splice(2, 1, {});
          break;
        case 3:
          break;
      }
      this.$forceUpdate();
    },

    /**
     * 移除某个选项
     * @param {*} type 层级类别
     * @param {*} paremtId 上级id
     * @param {*} index 当前的下标
     */
    handleCheckbox(type, paremtId, index) {
      console.log(type, paremtId, index);
      switch (type) {
        case "levelOne":
          // 1.如果删除的是当前选中的 删除的下标跟选中的一致将当前展示数据清空
          if (
            this.activeItem[0].levelName ===
            "1-" + this.levelOne[index].index
          ) {
            this.levelTwo = [];
            this.levelThree = [];
          }
          // 2.删除指定的数据
          this[type].splice(index, 1);
          break;
        case "levelTwo":
          // 1.如果删除的是当前选中的 删除的下标跟选中的一致将当前展示数据清空
          if (
            this.activeItem[1].levelName ===
            "2-" + this.levelTwo[index].index
          ) {
            this.levelThree = [];
          }
          // 2.删除指定的数据
          this.levelTwo.splice(index, 1); // 删除页面上展示的数据
          this.levelOne[this.activeItem[0].index - 1].children = this.levelTwo; // 删除真正存储的数据
          break;
        case "levelThree":
          this.levelThree.splice(index, 1);
          this.levelTwo[this.activeItem[1].index - 1].children = this.levelThree;
          this.levelOne[this.activeItem[0].index - 1].children = this.levelTwo;
          break;
      }
    },

    /**
     * 文本框输入检查
     * @param {*} type 层级类别
     * @param {*} value 输入的数据
     */
    inputBlur(type, value, index) {
      // console.log(value, index);
      if (value != "") {
        this[type].forEach((item, i) => {
          // 如果有相同的数据
          if (item.value == value && index != i) {
            this.$message.error("当前输入的数据已存在，请检查！");
            return;
          }
        });
      }
    },

    // 确定提交
    submit() {
      // const list = [
      //   ...this.levelOne,
      //   ...this.levelTwo,
      //   ...this.levelThree
      // ].reduce((prev, item, index) => {
      //   const arr = item.level.split("-");
      //   if (!prev[arr[0]]) {
      //     prev[arr[0]] = {
      //       level: arr[0],
      //       children: []
      //     };
      //   }
      //   prev[arr[0]]["children"].push(item);
      //   return prev;
      // }, {});
      // const result = Object.values(list);
      this.$emit("submit", this.levelOne);
    },

    // 关闭
    handleClose() {
      this.$emit("close", false);
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  height: 470px;
  .select-item {
    width: 265px;
    height: 100%;
    border: 1px solid #eee;
    .title {
      height: 35px;
      border-bottom: 1px solid #eee;
      line-height: 35px;
      padding-left: 15px;
    }
    .list-content {
      width: 100%;
      overflow-y: auto;
      text-align: center;
      .level-item {
        display: block;
        margin-left: 0;
        margin-top: 5px;
        line-height: 35px;
        padding: 15px 15px 0 15px;

        .input {
          display: inline-block;
          width: 200px;
          border: 1px solid #e6e6e6;
        }
        .input_active {
          border: 1px solid #0066f9;
        }
        .handle {
          cursor: pointer;
          color: #ccc;
          font-size: 20px;
        }
      }

      .create-btn {
        width: 200px;
        border: 1px dashed #0066f9;
        color: #0066f9;
        margin-top: 15px;
      }
    }
  }
}
/deep/ .el-input__inner {
  border: none;
}
</style>
